#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>

int main(int argc, char const *argv[])
{
	int fd;
	int ret;
	char *serialPath = "/dev/ttyUSB0";
	char *wbuffer = "hello world!\n";
	char rbuffer[32] = {0};
	struct termios termios;
	fd_set rfd;
	struct timeval timeval;
	int len = 0;
	if((fd = open(serialPath, O_RDWR | O_NOCTTY  |O_NDELAY)) < 0)
	{
		printf("open %s is failed",serialPath);
	}
	else
	{
		printf("open %s is success\n",serialPath);
		bzero(&termios, sizeof(termios)); 

		termios.c_cflag  |=  CLOCAL | CREAD;
		termios.c_cflag &= ~CSIZE;
		termios.c_cflag |= CS8;
		termios.c_cflag &= ~PARENB;
		termios.c_cflag &=  ~CSTOPB;
		cfsetispeed(&termios, B115200);
		cfsetospeed(&termios, B115200);
		termios.c_cc[VTIME]  = 0;
		termios.c_cc[VMIN] = 0;
		tcflush(fd, TCIFLUSH);
		if((tcsetattr(fd, TCSANOW, &termios)) != 0)
		{
			perror("com set error\n");
			return -1;
		}
		while(1)
		{
			FD_ZERO(&rfd);
       		FD_SET(fd, &rfd);
       		timeval.tv_sec = 10;            //10s内接收不到新数据即认为数据接收完成
       		timeval.tv_usec = 0;
       		ret = select(fd + 1, &rfd, NULL, NULL, &timeval);
       		if(ret == -1)
       		{
       			printf("select error\n");
       			break;
       		}
       		else if(ret == 0)
       		{
       			usleep(1000);               //未收到信息，系统调度
       			memset(rbuffer, 0, 32);
			    len = 0;
       		}
       		else
       		{
       			ret = read(fd, rbuffer + len, 32);   //保存信息
       			len += ret;
				printf("rbuffer is %s\n",rbuffer);
       		}
		}
	}
	close(fd);
	return 0;
}
